

from . import RSA
from . import pkcs1_15
from . import SHA256
from . import b64encode
from . import time
from . import random
from . import requests
from . import json


class WxPayUtil:
    '''
    微信支付
    '''

    mchid = '1604331286'
    serial_no = '721CF516C167847BE8651BBED1113233BE7C7A65'
    private_key = None

    def __init__(self) -> None:
        with open('apiclient_key.pem') as private_key_file:
            self.private_key = private_key_file.read()

    def __sign_str(self, method, url_path, request_body, timestamp, nonce_str):
        """
        生成签名字符串
        """
        sign_list = [
            method,
            url_path,
            timestamp,
            nonce_str,
            request_body
        ]
        return '\n'.join(sign_list) + '\n'

    def __sign(self, sign_str):
        """
        生成签名
        """
        rsa_key = RSA.importKey(self.private_key)
        signer = pkcs1_15.new(rsa_key)
        digest = SHA256.new(sign_str.encode('utf8'))
        sign = b64encode(signer.sign(digest)).decode('utf8')
        return sign

    def __authorization(self, method, url_path, request_body, timestamp, nonce_str):
        """
        生成Authorization
        """
        signstr = self.__sign_str(method, url_path, request_body,
                                  timestamp, nonce_str)
        s = self.__sign(signstr)
        authorization = 'WECHATPAY2-SHA256-RSA2048  ' \
            'mchid="{mchid}",' \
            'nonce_str="{nonce_str}",' \
            'signature="{sign}",' \
            'timestamp="{timestamp}",' \
            'serial_no="{serial_no}"'.\
            format(mchid=self.mchid,
                   nonce_str=nonce_str,
                   sign=s,
                   timestamp=timestamp,
                   serial_no=self.serial_no
                   )
        return authorization
    

    def wx_native_pay(self,totalPrice:float,orderId:str):
        '''
        获取微信 native 支付二维码
        '''


        url = "https://api.mch.weixin.qq.com/v3/pay/transactions/native"
        
        body = '{"amount": {"total": ' + str(totalPrice) + '},\
        "mchid": "'+self.mchid+'","description": "Order","out_trade_no": "'+orderId+'",\
            "appid": "wx03db1f740dd59921",\
                "notify_url": "https://www.qlcnb.club/admin/system/wxPay"}'
        timestamp = str(int(time.time()))
        nonce_str = str(random.randint(100000, 10000000))
        str_Authorization = self.__authorization('POST',
                                      '/v3/pay/transactions/native',
                                      body, timestamp, nonce_str)
        headers = {
            "Content-Type": "application/json",
            "User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)",
            "Accept": "application/json",
            "Authorization": str_Authorization
        }
        res = requests.post(url=url, data=body, headers=headers)
        res = json.loads(res.content)
        code_url = res.get("code_url")
        return code_url
